package forum;

import org.apache.log4j.Logger;

import java.sql.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

public class DBConnectie {

    private String DBName, DBUser, DBPass, SQLQuery;
    private Connection conn;
    private Statement stmt;
    private ResultSet result;


    static Logger logger = Logger.getLogger(DBConnectie.class.getName());

    public DBConnectie(String DBName, String DBUser, String DBPass) {
        this.DBName = DBName;
        this.DBUser = DBUser;
        this.DBPass = DBPass;
        loadDriver();
    }

    private void loadDriver() {
        try {
            logger.info("Start Load Driver");
            Class.forName("com.mysql.jdbc.Driver");
            logger.info("Load Driver Successful");
        } catch (Exception e) {
            logger.info("Load Driver Error!");
            logger.error(e.getMessage());
        }
    }

    public void connect() {
        try {
            logger.info("Start Connect to Database!");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/" + DBName + "?user=" + DBUser + "&password=" + DBPass);
            logger.info("Connect to Database Successful!");
        } catch (Exception e) {
            logger.error("Connect Error!");
            logger.error(e.getMessage());
        }
    }

    public ResultSet selectQuery(String SQLQuery) {
        this.SQLQuery = SQLQuery;
        try {
            logger.info("Start Execute Select!");
            stmt = conn.createStatement();
            result = stmt.executeQuery(SQLQuery);
            logger.info("Execute Select Successful!");
        } catch (Exception e) {
            logger.error("Select Error!");
            logger.error(e.getMessage());
        }
        return result;
    }

    public void query(String SQLQuery) {
        this.SQLQuery = SQLQuery;
        try {
            logger.info("Start Execute Query!");
            stmt = conn.createStatement();
            stmt.execute(SQLQuery);
            logger.info("Execute Query Successful!");
        } catch (Exception e) {
            logger.error("Query Error!");
            logger.error(e.getMessage());
        }
    }

    public void close() {
        try {
            logger.info("Start Close Statement!");
            if (stmt != null) stmt.close();
            logger.info("Statement Closed Successful!");
        } catch (Exception e) {
            logger.error("Statement Close Error!");
            logger.error(e.getMessage());
        }
        try {
            logger.info("Start Close Connect!");
            if (conn != null) conn.close();
            logger.info("Connect Closed Successful!");
        } catch (Exception e) {
            logger.error("Connect Close Error!");
            logger.error(e.getMessage());
        }
    }
}

